/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.miami.unix_storage.xmlinventory.classes;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;

/**
 *
 * @author Alex Lorenzo
 * This class writes to a file using a 'path name' and associated 'file name' 
 * in the constructor when instantiating the class. Note: In order to append
 * neatly to a logfile, for example, please ensure that your text is well 
 * formatted and includes things like new line characters '\n' and dates 
 * dd/mm/yyyy.
 */
public class XMLInventoryWriter {
    private BufferedWriter writer = null;
    private String towrite = null;
    private Path path = null;
    private Charset charset = Charset.forName("UTF-8");


    public String getToWrite() {
        return towrite;
    }

    public void setToWrite(String towrite) {
        this.towrite = towrite;
    }
    XMLInventoryWriter(String setpath, String filetowriteto){
        this.path = FileSystems.getDefault().getPath(setpath, filetowriteto);
        File f = new File(getPathFile());
        if (!f.isFile()){
            try {
                f.createNewFile();
            } catch (IOException ex) {
                System.err.format ("IOException: %s%n", ex);
            }
        }
    }
    public String getPathFile(){
        
        return this.path.toString();
    }
    public String WriteToFile(){
        if (getPathFile()==null){
            return "No Path Set!";
        } else {
            try (BufferedWriter writer = Files.newBufferedWriter(this.path, 
                    this.charset, StandardOpenOption.APPEND)){
            if (getToWrite() == null){
                    return "No Data to write, please call setToWrite method.";
            } else {
                    writer.write(getToWrite(), 0, getToWrite().length());
                    writer.close();
                    return String.format("String has been written to file:"
                            + " %s", getPathFile());
                    }
            } catch (IOException ex) {
                System.err.format ("IOException: %s%n", ex);
                return String.format("IOException: %s%n", ex);
            }
        }
    }
    
}
